package database.databaseAccessObjects;

import java.util.ArrayList;
import java.util.List;

import database.DatabaseHelpers.LocationConstants;
import database.DatabaseHelpers.VIPmeSQLiteHelper;
import database.Models.Location;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DAOLocation {
//has many checkins
	// Database fields
	private SQLiteDatabase database;
	private VIPmeSQLiteHelper dbHelper;
	private String[] allColumns = { LocationConstants.COLUMN_ID,
			LocationConstants.COLUMN_NAME };

	public DAOLocation(Context context) {
		dbHelper = new VIPmeSQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public Location createLocation(String name) {
		ContentValues values = new ContentValues();
		values.put(LocationConstants.COLUMN_NAME, name);
		long insertId = database.insert(LocationConstants.TABLE_LOCATION, null,
				values);
		Cursor cursor = database.query(LocationConstants.TABLE_LOCATION,
				allColumns, LocationConstants.COLUMN_ID + " = " + insertId, null,
				null, null, null);
		cursor.moveToFirst();
		Location newLoc = cursorToLocation(cursor);
		cursor.close();
		return newLoc;
	}

	public void deleteLocation(Location location) {
		long id = location.getId();
		System.out.println("Comment deleted with id: " + id);
		database.delete(LocationConstants.TABLE_LOCATION, LocationConstants.COLUMN_ID
				+ " = " + id, null);
	}
	public Location getLocationById(int locationID) {
		Cursor cursor = database.query(LocationConstants.TABLE_LOCATION,allColumns, LocationConstants.COLUMN_ID
				+ " = " + locationID, null, null, null, null);
		cursor.moveToFirst();
		return cursorToLocation(cursor);
	}
	public List<Location> getAllLocations() {
		List<Location> locations = new ArrayList<Location>();

		Cursor cursor = database.query(LocationConstants.TABLE_LOCATION,
				allColumns, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			Location comment = cursorToLocation(cursor);
			locations.add(comment);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return locations;
	}

	private Location cursorToLocation(Cursor cursor) {
		Location location = new Location();
		location.setId(cursor.getInt(0));
		location.setName(cursor.getString(1));
		return location;
	}
}
